home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 1.iso / util / tgrep20.zip / GREP.C < prev    next >
Text File  |  1994-04-03  |  17KB  |  760 lines

  1. /* grep.c - main driver file for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written July 1992 by Mike Haertel.  */
  19.  
  20. #include <errno.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <sys/types.h>
  24. #include <string.h>
  25. #include <memory.h>
  26. #include <fcntl.h>
  27. #include <io.h>
  28. #include <dir.h>
  29. #include <dos.h>
  30.  
  31. #include "getpagesize.h"
  32. #include "grep.h"
  33. #include "getopt.h"
  34.  
  35. #undef MAX
  36. #define MAX(A,B) ((A) > (B) ? (A) : (B))
  37.  
  38. /* Define flags declared in grep.h. */
  39. char *matcher;
  40. int match_icase;
  41. int match_words;
  42. int match_lines;
  43.  
  44. /* Functions we'll use to search. */
  45. static void (*compile)(char *, size_t);
  46. static char *(*execute)(char *, size_t, char **);
  47.  
  48. /* For error messages. */
  49. static char *prog;
  50. static char *filename;
  51. static int errseen;
  52.  
  53. /* Print a message and possibly an error string.  Remember
  54.    that something awful happened. */
  55. static void
  56. error( const char *mesg, int errnum)
  57. {
  58.   if (errnum)
  59.     fprintf(stderr, "%s: %s: %s\n", prog, mesg, strerror(errnum));
  60.   else
  61.     fprintf(stderr, "%s: %s\n", prog, mesg);
  62.   errseen = 1;
  63. }
  64.  
  65. /* Like error(), but die horribly after printing. */
  66. void
  67. fatal(mesg, errnum)
  68.      const char *mesg;
  69.      int errnum;
  70. {
  71.   error(mesg, errnum);
  72.   exit(2);
  73. }
  74.  
  75. /* Interface to handle errors and fix library lossage. */
  76. char *
  77. xmalloc(size)
  78.      size_t size;
  79. {
  80.   char *result;
  81.  
  82.   result = malloc(size);
  83.   if (size && !result)
  84.     fatal("memory exhausted", 0);
  85.   return result;
  86. }
  87.  
  88. /* Interface to handle errors and fix some library lossage. */
  89. char *
  90. xrealloc(
  91.      char *ptr,
  92.      size_t size)
  93. {
  94.   char *result;
  95.  
  96.   if (ptr)
  97.     result = realloc(ptr, size);
  98.   else
  99.     result = malloc(size);
  100.   if (size && !result)
  101.     fatal("memory exhausted", 0);
  102.   return result;
  103. }
  104.  
  105. #define valloc malloc
  106.  
  107. /* Hairy buffering mechanism for grep.  The intent is to keep
  108.    all reads aligned on a page boundary and multiples of the
  109.    page size. */
  110.  
  111. static char *buffer;        /* Base of buffer. */
  112. static size_t bufsalloc;    /* Allocated size of buffer save region. */
  113. static size_t bufalloc;        /* Total buffer size. */
  114. static int bufdesc;        /* File descriptor. */
  115. static char *bufbeg;        /* Beginning of user-visible stuff. */
  116. static char *buflim;        /* Limit of user-visible stuff. */
  117.  
  118. /* Reset the buffer for a new file.  Initialize
  119.    on the first time through. */
  120.  
  121. /* This value gets multiplied by 5. The default of
  122.  * 8192 would cause the size argument to read() and
  123.  * to be negative.
  124.  */
  125. #define BUFSALLOC 1024
  126.  
  127. void
  128. reset(
  129.      int fd)
  130. {
  131.   static int initialized;
  132.  
  133.   if (!initialized)
  134.     {
  135.       initialized = 1;
  136. #ifndef BUFSALLOC
  137.       bufsalloc = MAX(8192, getpagesize());
  138. #else
  139.       bufsalloc = BUFSALLOC;
  140. #endif
  141.       bufalloc = 5 * bufsalloc;
  142.       /* The 1 byte of overflow is a kludge for dfaexec(), which
  143.      inserts a sentinel newline at the end of the buffer
  144.      being searched.  There's gotta be a better way... */
  145.       buffer = valloc(bufalloc + 1);
  146.       if (!buffer)
  147.     fatal("memory exhausted", 0);
  148.       bufbeg = buffer;
  149.       buflim = buffer;
  150.     }
  151.   bufdesc = fd;
  152. }
  153.  
  154. /* Read new stuff into the buffer, saving the specified
  155.    amount of old stuff.  When we're done, 'bufbeg' points
  156.    to the beginning of the buffer contents, and 'buflim'
  157.    points just after the end.  Return count of new stuff. */
  158. static int
  159. fillbuf(
  160.      size_t save)
  161. {
  162.   char *nbuffer, *dp, *sp;
  163.   int cc;
  164.   static int pagesize;
  165.  
  166.   if (pagesize == 0 && (pagesize = getpagesize()) == 0)
  167.     abort();
  168.  
  169.   if (save > bufsalloc)
  170.     {
  171.       while (save > bufsalloc)
  172.     bufsalloc *= 2;
  173.       bufalloc = 5 * bufsalloc;
  174.       nbuffer = valloc(bufalloc + 1);
  175.       if (!nbuffer)
  176.     fatal("memory exhausted", 0);
  177.     }
  178.   else
  179.     nbuffer = buffer;
  180.  
  181.   sp = buflim - save;
  182.   dp = nbuffer + bufsalloc - save;
  183.   bufbeg = dp;
  184.   while (save--)
  185.     *dp++ = *sp++;
  186.  
  187.   /* We may have allocated a new, larger buffer.  Since
  188.      there is no portable vfree(), we just have to forget
  189.      about the old one.  Sorry. */
  190.   buffer = nbuffer;
  191.  
  192.   cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  193.  
  194.   if (cc > 0)
  195.     buflim = buffer + bufsalloc + cc;
  196.   else
  197.     buflim = buffer + bufsalloc;
  198.   return cc;
  199. }
  200.  
  201. /* Flags controlling the style of output. */
  202. static int out_quiet;        /* Suppress all normal output. */
  203. static int out_invert;        /* Print nonmatching stuff. */
  204. static int out_file;        /* Print filenames. */
  205. static int out_line;        /* Print line numbers. */
  206. static int out_byte;        /* Print byte offsets. */
  207. static int out_before;        /* Lines of leading context. */
  208. static int out_after;        /* Lines of trailing context. */
  209.  
  210. /* Internal variables to keep track of byte count, context, etc. */
  211. static size_t totalcc;        /* Total character count before bufbeg. */
  212. static char *lastnl;        /* Pointer after last newline counted. */
  213. static char *lastout;        /* Pointer after last character output;
  214.                    NULL if no character has been output
  215.                    or if it's conceptually before bufbeg. */
  216. static size_t totalnl;        /* Total newline count before lastnl. */
  217. static int pending;        /* Pending lines of output. */
  218.  
  219. static void
  220. nlscan(char *lim)
  221. {
  222.   char *beg;
  223.  
  224.   for (beg = lastnl; beg < lim; ++beg)
  225.     if (*beg == '\n')
  226.       ++totalnl;
  227.   lastnl = beg;
  228. }
  229.  
  230. static void
  231. prline(
  232.      char *beg,
  233.      char *lim,
  234.      char sep)
  235. {
  236.   if (out_file)
  237.     printf("%s%c", filename, sep);
  238.   if (out_line)
  239.     {
  240.       nlscan(beg);
  241.       printf("%d%c", ++totalnl, sep);
  242.       lastnl = lim;
  243.     }
  244.   if (out_byte)
  245.     printf("%lu%c", totalcc + (beg - bufbeg), sep);
  246.   fwrite(beg, 1, lim - beg, stdout);
  247.   if (ferror(stdout))
  248.     error("writing output", errno);
  249.   lastout = lim;
  250. }
  251.  
  252. /* Print pending lines of trailing context prior to LIM. */
  253. static void
  254. prpending(
  255.      char *lim)
  256. {
  257.   char *nl;
  258.  
  259.   if (!lastout)
  260.     lastout = bufbeg;
  261.   while (pending > 0 && lastout < lim)
  262.     {
  263.       --pending;
  264.       if ((nl = memchr(lastout, '\n', lim - lastout)) != 0)
  265.     ++nl;
  266.       else
  267.     nl = lim;
  268.       prline(lastout, nl, '-');
  269.     }
  270. }
  271.  
  272. /* Print the lines between BEG and LIM.  Deal with context crap.
  273.    If NLINESP is non-null, store a count of lines between BEG and LIM. */
  274. static void
  275. prtext(
  276.      char *beg,
  277.      char *lim,
  278.      int *nlinesp)
  279. {
  280.   static int used;        /* avoid printing "--" before any output */
  281.   char *bp, *p, *nl;
  282.   int i, n;
  283.  
  284.   if (!out_quiet && pending > 0)
  285.     prpending(beg);
  286.  
  287.   p = beg;
  288.  
  289.   if (!out_quiet)
  290.     {
  291.       /* Deal with leading context crap. */
  292.  
  293.       bp = lastout ? lastout : bufbeg;
  294.       for (i = 0; i < out_before; ++i)
  295.     if (p > bp)
  296.       do
  297.         --p;
  298.       while (p > bp && p[-1] != '\n');
  299.  
  300.       /* We only print the "--" separator if our output is
  301.      discontiguous from the last output in the file. */
  302.       if ((out_before || out_after) && used && p != lastout)
  303.     puts("--");
  304.  
  305.       while (p < beg)
  306.     {
  307.       nl = memchr(p, '\n', beg - p);
  308.       prline(p, nl + 1, '-');
  309.       p = nl + 1;
  310.     }
  311.     }
  312.  
  313.   if (nlinesp)
  314.     {
  315.       /* Caller wants a line count. */
  316.       for (n = 0; p < lim; ++n)
  317.     {
  318.       if ((nl = memchr(p, '\n', lim - p)) != 0)
  319.         ++nl;
  320.       else
  321.         nl = lim;
  322.       if (!out_quiet)
  323.         prline(p, nl, ':');
  324.       p = nl;
  325.     }
  326.       *nlinesp = n;
  327.     }
  328.   else
  329.     if (!out_quiet)
  330.       prline(beg, lim, ':');
  331.  
  332.   pending = out_after;
  333.   used = 1;
  334. }
  335.  
  336. static char *
  337. expand_wildcards(char *s)
  338. {
  339.     static    struct find_t info;
  340.     char wildcard[80];
  341.     static char directory[256];
  342.     static char filename[256];
  343.     unsigned attrib;
  344.     char *c1, *c2;
  345.  
  346.     if (s)
  347.     {
  348.         strcpy(wildcard, s);
  349.         strcpy(directory, wildcard);
  350.             if ((c1 = strrchr(directory, '/')) != 0 ||
  351.             (c2 = strrchr(directory, '\\')) != 0)
  352.             {
  353.             if (c1 > c2)
  354.                 c1[1] = '\0';
  355.             else
  356.                 c2[1] = '\0';
  357.         }
  358.         else
  359.             directory[0] = '\0';
  360.         if (! strchr(wildcard, '.'))
  361.             strcat(wildcard, "*.*");
  362.         attrib = _A_NORMAL | _A_SUBDIR | _A_RDONLY;
  363.         if (_dos_findfirst(wildcard, attrib, &info) != 0)
  364.             return NULL;
  365.         while (!strcmp(info.name, ".") || !strcmp(info.name, ".."))
  366.             if (_dos_findnext(&info))
  367.                 return NULL;
  368.     }
  369.     else
  370.     {
  371.         if (_dos_findnext(&info) != 0)
  372.             return NULL;
  373.     }
  374.     strcpy(filename, directory);
  375.     strcat(filename, info.name);
  376.     return filename;
  377. }
  378.  
  379. /* Scan the specified portion of the buffer, matching lines (or
  380.    between matching lines if OUT_INVERT is true).  Return a count of
  381.    lines printed. */
  382. static int
  383. grepbuf(
  384.      char *beg,
  385.      char *lim)
  386. {
  387.   int nlines, n;
  388.   register char *p, *b;
  389.   char *endp;
  390.  
  391.   nlines = 0;
  392.   p = beg;
  393.   while ((b = (*execute)(p, lim - p, &endp)) != 0)
  394.     {
  395.       /* Avoid matching the empty line at the end of the buffer. */
  396.       if (b == lim && ((b > beg && b[-1] == '\n') || b == beg))
  397.     break;
  398.       if (!out_invert)
  399.     {
  400.       prtext(b, endp, (int *) 0);
  401.       nlines += 1;
  402.     }
  403.       else if (p < b)
  404.     {
  405.       prtext(p, b, &n);
  406.       nlines += n;
  407.     }
  408.       p = endp;
  409.     }
  410.   if (out_invert && p < lim)
  411.     {
  412.       prtext(p, lim, &n);
  413.       nlines += n;
  414.     }
  415.   return nlines;
  416. }
  417.  
  418. /* Search a given file.  Return a count of lines printed. */
  419. static int
  420. grep(
  421.      int fd)
  422. {
  423.   int nlines, i;
  424.   size_t residue, save;
  425.   char *beg, *lim;
  426.  
  427.   reset(fd);
  428.  
  429.   totalcc = 0;
  430.   lastout = 0;
  431.   totalnl = 0;
  432.   pending = 0;
  433.  
  434.   nlines = 0;
  435.   residue = 0;
  436.   save = 0;
  437.  
  438.   for (;;)
  439.     {
  440.       if (fillbuf(save) < 0)
  441.     {
  442.       error(filename, errno);
  443.       return nlines;
  444.     }
  445.       lastnl = bufbeg;
  446.       if (lastout)
  447.     lastout = bufbeg;
  448.       if (buflim - bufbeg == save)
  449.     break;
  450.       beg = bufbeg + save - residue;
  451.       for (lim = buflim; lim > beg && lim[-1] != '\n'; --lim)
  452.     ;
  453.       residue = buflim - lim;
  454.       if (beg < lim)
  455.     {
  456.       nlines += grepbuf(beg, lim);
  457.       if (pending)
  458.         prpending(lim);
  459.     }
  460.       i = 0;
  461.       beg = lim;
  462.       while (i < out_before && beg > bufbeg && beg != lastout)
  463.     {
  464.       ++i;
  465.       do
  466.         --beg;
  467.       while (beg > bufbeg && beg[-1] != '\n');
  468.     }
  469.       if (beg != lastout)
  470.     lastout = 0;
  471.       save = residue + lim - beg;
  472.       totalcc += buflim - bufbeg - save;
  473.       if (out_line)
  474.     nlscan(beg);
  475.     }
  476.   if (residue)
  477.     {
  478.       nlines += grepbuf(bufbeg + save - residue, buflim);
  479.       if (pending)
  480.     prpending(buflim);
  481.     }
  482.   return nlines;
  483. }
  484.  
  485. static char version[] = "GNU grep version 2.0 for TKERN";
  486.  
  487. #define USAGE \
  488.   "usage: %s [-[[AB] ]<num>] [-[CEFGVchilnqsvwx]] [-[ef]] <expr> [<files...>]\n"
  489.  
  490. static void
  491. usage(void)
  492. {
  493.   fprintf(stderr, USAGE, prog);
  494.   exit(2);
  495. }
  496.  
  497. /* Go through the matchers vector and look for the specified matcher.
  498.    If we find it, install it in compile and execute, and return 1.  */
  499. int
  500. setmatcher(
  501.      char *name)
  502. {
  503.   int i;
  504.  
  505.   for (i = 0; matchers[i].name; ++i)
  506.     if (strcmp(name, matchers[i].name) == 0)
  507.       {
  508.     compile = matchers[i].compile;
  509.     execute = matchers[i].execute;
  510.     return 1;
  511.       }
  512.   return 0;
  513. }  
  514.  
  515. int
  516. main(argc, argv)
  517.      int argc;
  518.      char *argv[];
  519. {
  520.   char *keys;
  521.   size_t keycc, oldcc, keyalloc;
  522.   int keyfound, count_matches, no_filenames, list_files, suppress_errors;
  523.   int opt, cc, desc, count, status;
  524.   FILE *fp;
  525.   extern char *optarg;
  526.   extern int optind;
  527.   char *this_filename;
  528.  
  529.   prog = argv[0];
  530.   if (prog && strrchr(prog, '/'))
  531.     prog = strrchr(prog, '/') + 1;
  532.  
  533.   keys = NULL;
  534.   keycc = 0;
  535.   keyfound = 0;
  536.   count_matches = 0;
  537.   no_filenames = 0;
  538.   list_files = 0;
  539.   suppress_errors = 0;
  540.   matcher = NULL;
  541.  
  542.   while ((opt = getopt(argc, argv, "0123456789A:B:CEFGVX:bce:f:hiLlnqsvwxy"))
  543.      != EOF)
  544.     switch (opt)
  545.       {
  546.       case '0':
  547.       case '1':
  548.       case '2':
  549.       case '3':
  550.       case '4':
  551.       case '5':
  552.       case '6':
  553.       case '7':
  554.       case '8':
  555.       case '9':
  556.     out_before = 10 * out_before + opt - '0';
  557.     out_after = 10 * out_after + opt - '0';
  558.     break;
  559.       case 'A':
  560.     out_after = atoi(optarg);
  561.     if (out_after < 0)
  562.       usage();
  563.     break;
  564.       case 'B':
  565.     out_before = atoi(optarg);
  566.     if (out_before < 0)
  567.       usage();
  568.     break;
  569.       case 'C':
  570.     out_before = out_after = 2;
  571.     break;
  572.       case 'E':
  573.     if (matcher && strcmp(matcher, "egrep") != 0)
  574.       fatal("you may specify only one of -E, -F, or -G", 0);
  575.     matcher = "posix-egrep";
  576.     break;
  577.       case 'F':
  578.     if (matcher && strcmp(matcher, "fgrep") != 0)
  579.       fatal("you may specify only one of -E, -F, or -G", 0);;
  580.     matcher = "fgrep";
  581.     break;
  582.       case 'G':
  583.     if (matcher && strcmp(matcher, "grep") != 0)
  584.       fatal("you may specify only one of -E, -F, or -G", 0);
  585.     matcher = "grep";
  586.     break;
  587.       case 'V':
  588.     fprintf(stderr, "%s\n", version);
  589.     break;
  590.       case 'X':
  591.     if (matcher)
  592.       fatal("matcher already specified", 0);
  593.     matcher = optarg;
  594.     break;
  595.       case 'b':
  596.     out_byte = 1;
  597.     break;
  598.       case 'c':
  599.     out_quiet = 1;
  600.     count_matches = 1;
  601.     break;
  602.       case 'e':
  603.     cc = strlen(optarg);
  604.     keys = xrealloc(keys, keycc + cc + 1);
  605.     if (keyfound)
  606.       keys[keycc++] = '\n';
  607.     strcpy(&keys[keycc], optarg);
  608.     keycc += cc;
  609.     keyfound = 1;
  610.     break;
  611.       case 'f':
  612.     fp = strcmp(optarg, "-") != 0 ? fopen(optarg, "r") : stdin;
  613.     if (!fp)
  614.       fatal(optarg, errno);
  615.     for (keyalloc = 1; keyalloc <= keycc; keyalloc *= 2)
  616.       ;
  617.     keys = xrealloc(keys, keyalloc);
  618.     oldcc = keycc;
  619.     if (keyfound)
  620.       keys[keycc++] = '\n';
  621.     while (!feof(fp)
  622.            && (cc = fread(keys + keycc, 1, keyalloc - keycc, fp)) > 0)
  623.       {
  624.         keycc += cc;
  625.         if (keycc == keyalloc)
  626.           keys = xrealloc(keys, keyalloc *= 2);
  627.       }
  628.     if (fp != stdin)
  629.       fclose(fp);
  630.     /* Nuke the final newline to avoid matching a null string. */
  631.     if (keycc - oldcc > 0 && keys[keycc - 1] == '\n')
  632.       --keycc;
  633.     keyfound = 1;
  634.     break;
  635.       case 'h':
  636.     no_filenames = 1;
  637.     break;
  638.       case 'i':
  639.       case 'y':            /* For old-timers . . . */
  640.     match_icase = 1;
  641.     break;
  642.       case 'L':
  643.     /* Like -l, except list files that don't contain matches.
  644.        Inspired by the same option in Hume's gre. */
  645.     out_quiet = 1;
  646.     list_files = -1;
  647.     break;
  648.       case 'l':
  649.     out_quiet = 1;
  650.     list_files = 1;
  651.     break;
  652.       case 'n':
  653.     out_line = 1;
  654.     break;
  655.       case 'q':
  656.     out_quiet = 1;
  657.     break;
  658.       case 's':
  659.     suppress_errors = 1;
  660.     break;
  661.       case 'v':
  662.     out_invert = 1;
  663.     break;
  664.       case 'w':
  665.     match_words = 1;
  666.     break;
  667.       case 'x':
  668.     match_lines = 1;
  669.     break;
  670.       default:
  671.     usage();
  672.     break;
  673.       }
  674.  
  675.   if (!keyfound)
  676.     if (optind < argc)
  677.       {
  678.     keys = argv[optind++];
  679.     keycc = strlen(keys);
  680.       }
  681.     else
  682.       usage();
  683.  
  684.   if (!matcher)
  685.     matcher = prog;
  686.  
  687.   if (!setmatcher(matcher) && !setmatcher("default"))
  688.     abort();
  689.  
  690.   (*compile)(keys, keycc);
  691.  
  692.   if (argc - optind > 1 && !no_filenames)
  693.     out_file = 1;
  694.   else if (optind < argc)
  695.   {
  696.     if (expand_wildcards(argv[optind]) && expand_wildcards(0))
  697.     out_file = 1;
  698.     while (expand_wildcards(0));
  699.   }
  700.  
  701.   status = 1;
  702.  
  703.   if (optind < argc)
  704.     while (optind < argc)
  705.       {
  706.     for (this_filename = expand_wildcards(argv[optind]);
  707.          this_filename;
  708.          this_filename = expand_wildcards(0))
  709.     {
  710.         desc = strcmp(this_filename, "-") ?
  711.             open(this_filename, O_RDONLY, 0) : 0;
  712.         if (desc < 0)
  713.           {
  714.             if (!suppress_errors)
  715.               error(argv[optind], errno);
  716.           }
  717.         else
  718.           {
  719.             filename = desc == 0 ? "(standard input)" : this_filename;
  720.             count = grep(desc);
  721.             if (count_matches)
  722.               {
  723.             if (out_file)
  724.               printf("%s:", filename);
  725.             printf("%d\n", count);
  726.               }
  727.             if (count)
  728.               {
  729.             status = 0;
  730.             if (list_files == 1)
  731.               printf("%s\n", filename);
  732.               }
  733.             else if (list_files == -1)
  734.               printf("%s\n", filename);
  735.           }
  736.         if (desc != 0)
  737.           close(desc);
  738.     }
  739.     ++optind;
  740.       }
  741.   else
  742.     {
  743.       filename = "(standard input)";
  744.       count = grep(0);
  745.       if (count_matches)
  746.     printf("%d\n", count);
  747.       if (count)
  748.     {
  749.       status = 0;
  750.       if (list_files == 1)
  751.         printf("(standard input)\n");
  752.     }
  753.       else if (list_files == -1)
  754.     printf("(standard input)\n");
  755.     }
  756.  
  757.   exit(errseen ? 2 : status);
  758.   return 0;
  759. }
  760.